package org.csu.linkgame.service.ClassForDoubleGame;


import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.List;

/**
 * 描述:连连看单元格
 *
 * @author hanxi
 *
 */
public class dgTile extends Parent implements Serializable {
    // 记录单元格位置
    public ObjectProperty<dgPoint> index = new SimpleObjectProperty<dgPoint>();
    // 单元格类型
    public StringProperty type = new SimpleStringProperty();
    // 所在画布对象
    public dgServiceImpl canvas;
    // 是否可点击
    public boolean clickable = true;
    // 用于点击后实现单元格特效
    private DoubleProperty strokeAlpha = new SimpleDoubleProperty(0.0);
    public Timeline fade = new Timeline();
    // 单元格图片
    private ObjectProperty<Image> imageProperty = new SimpleObjectProperty<Image>();
    // 单元格边框颜色
    private ObjectProperty<Color> colorProperty = new SimpleObjectProperty<Color>();

    // 用于变化两个单元格位置时临时存储Point
    public dgPoint tempPoint;

    // socket
    public Socket socket = null;
    public dgTile(final dgServiceImpl canvas, dgPoint index, Image image) {
        initArgs();
        this.index.set(index);
        this.canvas = canvas;
        //this.type.set(type);
        imageProperty.set(image);
        this.strokeAlpha.set(0);
        getChildren().add(create());
        setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                handleAction();
            }
        });
    }

    // 点击事件处理
    private void handleAction() {
        // 不可点击，说明已经不存在了，直接返回
        if (!clickable) {
            return;
        }
        // 第一次点击,用于选择开始连接点
        if (canvas.tempStart == null) {
            canvas.tempStart = this;
            fade.setRate(10);
            fade.play();
            return;
        }// 开始连接点已经选好
        else {
            if (canvas.tempStart == this) {
                canvas.tempStart = null;
                fade.setRate(-10);
                fade.play();
                return;
            } else {
                canvas.tempEnd = this;
                canvas.tempStart.fade.setRate(-10);
                canvas.tempStart.fade.play();
                canvas.tempEnd.fade.setRate(10);
                canvas.tempEnd.fade.play();
                // 如果类型相同，则查找连接路径
                if (canvas.tempStart.getType().equals(canvas.tempEnd.getType())) {
                    List<dgPoint> path = canvas.findPath(
                            canvas.tempStart.getPoint(),
                            canvas.tempEnd.getPoint());
                    if (path != null) {
                        canvas.tempStart.clickable = false;
                        canvas.tempEnd.clickable = false;
                        canvas.tempStart = null;
                        canvas.tempEnd = null;
                        canvas.drawLine(path);
                        doubleGameData.goals++;
                        System.out.println("用户此时向服务器传递path信息");
                        ObjectOutputStream os = null;
                        ObjectInputStream is = null;
                        try {
                            os = new ObjectOutputStream(this.socket.getOutputStream());
                            os.writeObject(path);
                            os.flush();
                        }catch (Exception o){
                            o.printStackTrace();
                        }

/*                        is = new ObjectInputStream(new BufferedInputStream(canvas.socket.getInputStream()));
                        Object obj = is.readObject();
                        if (obj != null) {
                            user = (User)obj;
                            System.out.println("user: " + user.getName() + "/" + user.getPassword());
                        }*/

                    } else {
                        canvas.tempStart = canvas.tempEnd;
                        canvas.tempEnd = null;
                    }
                } else {
                    canvas.tempStart = canvas.tempEnd;
                    canvas.tempEnd = null;
                }
            }

        }
    }

    private void initArgs() {
        index.addListener(new ChangeListener<dgPoint>() {
            @Override
            public void changed(ObservableValue<? extends dgPoint> observable,
                                dgPoint oldValue, dgPoint newValue) {
                tempPoint = newValue;
                setTranslateX(newValue.col * (dgUtils.ELEMENTSIZE + 5) + 60);
                setTranslateY(newValue.row * (dgUtils.ELEMENTSIZE + 5) + 60);
            }
        });
        /*type.addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                                String oldValue, Image newValue) {
                //String temp = "file:D:\\软件工程实验\\实训\\java实训\\src\\main\\java\\org\\csu\\linkgame\\service\\ClassForGame\\images\\";
                String temp = "http://orange-1312206514.cos.ap-guangzhou.myqcloud.com/images/";
                String resultValue = temp+newValue;
                //System.out.println(resultValue);
                Image image = new Image(resultValue, dgUtils.ELEMENTSIZE - 5,
                        dgUtils.ELEMENTSIZE - 5, true, true);
            }
        });*/
        strokeAlpha.addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable,
                                Number oldValue, Number newValue) {
                Color color = Color.color(0, 0.8, 0, newValue.doubleValue());
                colorProperty.set(color);
            }
        });
        KeyFrame frame1 = new KeyFrame(Duration.ZERO, new KeyValue(strokeAlpha,
                0, Interpolator.LINEAR));
        KeyFrame frame2 = new KeyFrame(Duration.millis(500), new KeyValue(
                strokeAlpha, 1, Interpolator.LINEAR));
        fade.getKeyFrames().addAll(frame1, frame2);
    }

    // 生成单元格UI
    private Node create() {
        Group group = new Group();
        Rectangle rec = new Rectangle(dgUtils.ELEMENTSIZE, dgUtils.ELEMENTSIZE,
                Color.WHITE);
        rec.strokeProperty().bind(colorProperty);
        rec.setStrokeWidth(3);
        rec.setArcWidth(10);
        rec.setArcHeight(10);

        ImageView view = new ImageView();
        view.setTranslateX(3);
        view.setTranslateY(3);
        view.imageProperty().bind(imageProperty);
        group.getChildren().addAll(rec, view);
        return group;
    }

    public Image getType() {
        return imageProperty.get();
    }

    public dgPoint getPoint() {
        return index.get();
    }

    @Override
    public String toString() {
        return "[" + getPoint().row + "," + getPoint().col + "]";
    }
}
